//
//  ZFFeedbackViewController.m
//  HappilyLoan
//
//  Created by zainishenbian on 2017/3/27.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "ZFFeedbackViewController.h"
#import "ZFMyConfig.h"
#import "ZFHeader.h"
#import "AlertBoxView.h"
#import "ZFHttpTool.h"

@interface ZFFeedbackViewController ()<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UICollectionView *collectV;
    UITextView *textV;
    NSMutableArray *imgCountArray;//图片数量
    UIImageView *lastSelectImgV;//上次长按选中的图片
    UIButton *_button;
}
@property(nonatomic,strong)AlertBoxView *alertBox;
@property (nonatomic,strong)AnimatingView *anima;
@end

@implementation ZFFeedbackViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"feedBack"];
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [_anima stopTheAnimation];
    [MobClick endLogPageView:@"feedBack"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"意见反馈";
    self.automaticallyAdjustsScrollViewInsets=NO;

    imgCountArray = [NSMutableArray new];
    UIImage *addImg = [UIImage imageNamed:@"添加图片"];
    [imgCountArray addObject:addImg];

    [self setTextView];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (SCREEN_WIDTH-20-10*3)/4;
    layout.itemSize = CGSizeMake(width, width);

    collectV = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 260, SCREEN_WIDTH-20, SCREEN_HEIGHT-280) collectionViewLayout:layout];
    collectV.delegate = self;
    collectV.backgroundColor = BGCOLOR;
    collectV.dataSource = self;
    [self.view addSubview:collectV];
    //注册单元格
    [collectV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [collectV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"headerCell"];
    [self.view addSubview:self.alertBox];
    [_button setShadowWidth:2 shadowHeight:2 shadowColor:Main_Color1 radius:10];
    self.anima = [[AnimatingView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

}
//设置信息view
- (void)setTextView
{
    textV = [[UITextView alloc] init];
    textV.text = @"您宝贵的意见是我们前行的最大动力！";
    textV.delegate = self;
    [self.view addSubview:textV];
    [textV mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(74);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(170);
    }];
}

#pragma mark ———— textview delegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"您宝贵的意见是我们前行的最大动力！"])
    {
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length < 1)
    {
        textView.text = @"您宝贵的意见是我们前行的最大动力！";
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@""] && range.length > 0) {
        //删除字符肯定是安全的
        return YES;
    }
    else
    {
        if (textView.text.length - range.length + text.length > 200) {
            
            UIAlertController *alert=[UIAlertController alertControllerWithTitle:nil message:@"超出最大可输入长度" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * sureAct1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:sureAct1];
            [self presentViewController:alert animated:NO completion:nil];

//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"超出最大可输入长度" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alert show];
            return NO;
        }
        else {
            return YES;
        }
    }
}
#pragma mark ———— collectview delegate ，collectView DataSource
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerCell" forIndexPath:indexPath];
    
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.backgroundColor = Main_Color1;
    [_button setTitle:@"提交反馈" forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(submitFeedback:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:_button];
    [_button mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(30);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(44);
    }];
    return headView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 74);
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return imgCountArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    for (UIView *view in cell.contentView.subviews) {
        
        [view removeFromSuperview];
    }
    if (indexPath.row < imgCountArray.count-1) {
        
        UIImageView *imgV = [[UIImageView alloc] init];
        imgV.image = imgCountArray[indexPath.row];
        imgV.tag = indexPath.row + 1;
        imgV.userInteractionEnabled = YES;
        imgV.backgroundColor = Main_Color1;
        [cell.contentView addSubview:imgV];
        [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.mas_equalTo(cell.contentView.mas_centerX);
            make.centerY.mas_equalTo(cell.contentView.mas_centerY);
            make.top.mas_equalTo(7);
            make.right.mas_equalTo(-7);
        }];
        //为imgV添加点击手势
        UITapGestureRecognizer *tapImg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(preViewImg:)];
        [imgV addGestureRecognizer:tapImg];
        //为imgV添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressImg:)];
        [imgV addGestureRecognizer:longPress];
    }
    else
    {
        UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [addButton setBackgroundImage:imgCountArray[indexPath.row] forState:UIControlStateNormal];
        [addButton addTarget:self action:@selector(addImgV:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:addButton];
        
        [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.mas_equalTo(cell.contentView.mas_centerX);
            make.centerY.mas_equalTo(cell.contentView.mas_centerY);
            make.top.mas_equalTo(7);
            make.right.mas_equalTo(-7);
        }];
    }
    
    return cell;
}
#pragma mark ———— UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [imgCountArray insertObject:image atIndex:0];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [collectV reloadData];
}
#pragma mark ———— button的点击事件
//添加图片
- (void)addImgV:(UIButton *)button
{
    if (imgCountArray.count >= 6) {
        [_alertBox appearAndDisappearAlertWithString:@"图片不超过五张"];
        return;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
//删除图片
- (void)delegaetImg:(UIButton *)button
{
    UICollectionViewCell *cell = (UICollectionViewCell *)button.superview.superview;
    NSIndexPath *indxpath = [collectV indexPathForCell:cell];
    [imgCountArray removeObjectAtIndex:indxpath.row];

    for (UIView *view in button.superview.subviews) {
        
        [view removeFromSuperview];
                NSLog(@"%@",button.superview.superview);
    }
    
    [collectV reloadData];
}
//提交反馈
- (void)submitFeedback:(UIButton *)button
{
    if (textV.text.length < 20) {
        
        [self showAlertView:@"反馈内容不少于20字"];
        return;
    }
    else if (imgCountArray.count < 4) {
        
        [self showAlertView:@"图片不少于3张"];
        return;
    }
//    NSMutableArray *imgDataArray = [[NSMutableArray alloc] init];
//    NSData *imageData = [NSData dataWithContentsOfFile:imgCountArray];
//    [imgDataArray addObject:imageData];
//    [ZFMyInfoHttpRequest requestFeedBackUser_id:nil feedBack_content:textV.text photo_files:nil sucessBlock:^(NSDictionary *dict) {
//        
//    } failureBlock:^(NSInteger failSign) {
//        
//    }];
    
    [self performSelector:@selector(loadDoneFeed) withObject:nil afterDelay:3.0];
    [_anima startTheAnimation];
    
}
- (void)loadDoneFeed{
    [_anima stopTheAnimation];
     [self performSelector:@selector(DoneLoad) withObject:nil afterDelay:1.0];
    [_alertBox appearAndDisappearAlertWithString:@"提交成功"];
}
- (void)DoneLoad{
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark ———— imageview 点击事件
//点击预览事件
- (void)preViewImg:(UITapGestureRecognizer *)tap
{
    //图片预览
    [ZFMyConfig showBigImage:(UIImageView *)tap.view];
}
//长按显示删除按钮
- (void)longPressImg:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {

        for (UIView *view in lastSelectImgV.superview.subviews) {
            
            if ([view isKindOfClass:[UIButton class]]) {
                
                [view removeFromSuperview];
            }
        }
        
        UIView *cellV = longPress.view.superview;
        UIButton *delegateButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [delegateButton setImage:[UIImage imageNamed:@"删除图片"] forState:UIControlStateNormal];
        [delegateButton addTarget:self action:@selector(delegaetImg:) forControlEvents:UIControlEventTouchUpInside];
        [cellV addSubview:delegateButton];
        [delegateButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.right.top.mas_equalTo(0);
            make.top.mas_offset(0);
            make.width.mas_equalTo(15);
            make.height.mas_equalTo(15);
        }];
        lastSelectImgV = (UIImageView *)longPress.view;
    }
}
- (AlertBoxView *)alertBox
{
    if (!_alertBox) {
        _alertBox = [[AlertBoxView alloc] init];
    }
    return _alertBox;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
